import React, {Component} from 'react'
import {observer} from 'mobx-react';
import { withRouter } from 'react-router-dom';
import {DateSwitch} from 'weaver-mobile';
import { MapPage } from "weaver-mobile-page";

const Normal = MapPage.Normal;
let map;

@withRouter
@observer
export default class Map extends Component {
  mapEvents = {
    created: instance => this.setMapInstance(instance)
  };

  setMapInstance = instance => {
      if (instance.CLASS_NAME === "AMap.Map") {
          map = instance;
          const {
            setSearchDate,
            moment
          } = this.props.store;
          setSearchDate(moment().format('YYYY-MM-DD'), datas => this.initMarker(datas));
      }
  }

  initMarker = datas => {
    try{
      if(map != null){
        map.clearMap();
        let marker;
        let line ;
        let positions = [];
        datas.map((d, index) => {
          if(d.position && d.position.longitude != null){
            const position = [d.position.longitude, d.position.latitude]
            marker = new window.AMap.Marker({
                position,
                content: `<div class='markerContent markerRBg'>${index + 1}</div>`,
                offset: new window.AMap.Pixel(-17, -34),
            });
            map.add(marker);
            positions.push(position);
          }
        });
        if(positions.length > 0){
          line = new window.AMap.Polyline({
            path: positions,
            strokeColor: '#55B1F9'
          });
          map.add(line);
        }
        
        setTimeout(() => {
          this.setFitView();
        }, 100)
      }
    }catch(e){}
  }

  setFitView = () => {
    const overlaysList = map.getAllOverlays('marker');
    map.setFitView(overlaysList);
  }

  render() {
    const mapProps = {
      showIntroduction: false,
      events: this.mapEvents,
      children: <div />
    }
    const {searchDate, toJS, setSearchDate} = this.props.store;
    return (
        <div className='map'>
          <Normal {...mapProps}>
            <div className='dateSwitch'>
              <DateSwitch date={searchDate} onChange={date => setSearchDate(date, datas => this.initMarker(datas))}/>
            </div>
          </Normal>
        </div>
    );
  }
}